import PureUnitDeploy from '../components/unit-deploy';
import * as RunnableUnitAction from 'actions/runnable-unit';
import { getFetchStatus } from 'actions/util';
import * as React from 'react';
import * as ReactRedux from 'react-redux';

const mapStateToProps = (state, ownProps) => {
  const unitId = ownProps.unitId;
  const unit = state.runnableUnitsById[unitId];
  let title;
  if (unit.type === 'MAVEN_SUB') {
    const parentUnit = state.runnableUnitsById[unit.parentId];
    title = `${parentUnit.key}/${unit.url}`;
  } else {
    title = unit.key;
  }

  return {
    // TODO 部署/重启之类动作的 fetching 可以和这个 或 起来
    fetching: getFetchStatus(state, RunnableUnitAction.listSuccessBuildsByUnit, unitId),
    builds: state.successBuildListByUnit[unitId] || [],
    deployLogs: state.deployLogListByUnit[unitId] || [],
    machines: unit.machineList,
    title
  };
};

const mapDispatchToProps = (dispatch, ownProps) => {
  const unitId = ownProps.unitId;

  return {
    listBuilds: () => {
      return dispatch(RunnableUnitAction.listSuccessBuildsByUnit(unitId));
    },
    listDeployLog: () => {
      return dispatch(RunnableUnitAction.listDeployLogByUnit(unitId));
    },
    restartUnit: (image, machineIds) => {
      return dispatch(RunnableUnitAction.restartUnit(unitId, image, machineIds))
        .then(() => dispatch(RunnableUnitAction.listDeployLogByUnit(unitId)));
    },
    startUnit: (image, machineIds) => {
      return dispatch(RunnableUnitAction.startUnit(unitId, image, machineIds))
        .then(() => dispatch(RunnableUnitAction.listDeployLogByUnit(unitId)));
    },
    stopUnit: (image, machineIds) => {
      return dispatch(RunnableUnitAction.stopUnit(unitId, image, machineIds))
        .then(() => dispatch(RunnableUnitAction.listDeployLogByUnit(unitId)));
    }
  };
};

class UnitDeploy extends React.Component {
  componentDidMount() {
    this.props.listBuilds();
    this.props.listDeployLog();
  }

  render() {
    return <PureUnitDeploy {...this.props}/>;
  }
}

export default ReactRedux.connect(mapStateToProps, mapDispatchToProps)(UnitDeploy);
